<template>
  <!-- Home 首页 -->
  <PageContainer>
    <view style="background-color: #fff">
      <Header title="" transparent="auto" varietyTitleColor="#000" :is-go-back="false">
        <template #header>
          <view class="home-title disFlxAC justify-center" :style="getHomeHeaderStyles">
            {{ globalConfig?.name }}
          </view>
        </template>
      </Header>
      <view class="home-bg" :style="{ background: getBackground }"></view>
      <view class="container">
        <Banner :list="bannerInfo" :loading="_loading" />
        <view class="mt-15">
          <TabList :list="diamondRegionInfo" :loading="_loading" />
        </view>

        <view class="borderTop pl-15 pr-15" v-if="_loading || groupConfigInfo.length">
          <Special :list="groupConfigInfo" :loading="_loading" />
          <view
            v-if="specialTotal >= specialLimit"
            class="moreBox flexCenter pb-15 fz-14"
            @click="navigateTo({ name: 'specialList' })"
          >
            <view class="pb-1">更多</view>
            <text class="ali-icon fz-24">&#xe6c7;</text>
          </view>
        </view>

        <!-- 福利模块 -->
        <view v-if="memberBenefitsInfo?.length" class="pl-15 pr-15">
          <WelfareModule :list="memberBenefitsInfo" />
        </view>

        <template v-if="_loading || activityInfo">
          <view class="borderTop pl-15 pr-15">
            <view class="box-title">
              <view class="fz-16 fw-7" :class="{ _skeleton: _loading }">
                <text>热门活动</text>
              </view>
              <view
                class="fz-14 moreBox"
                :class="{ _skeleton: _loading }"
                @click="navigateTo({ name: 'activity', options: {} })"
              >
                <view>更多</view>
                <text class="ali-icon fz-24">&#xe6c7;</text>
              </view>
            </view>
            <view class="py-15">
              <template v-if="activityInfo">
                <ActivityItem :item="activityInfo" @refresh="getData" />
              </template>
              <template v-else>
                <view
                  class="_skeleton br-10"
                  style="height: 496rpx; box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.15)"
                ></view>
              </template>
            </view>
          </view>
        </template>

        <view class="borderTop pl-15 pr-15" v-if="_loading || photoAlbumInfo.length">
          <view class="box-title">
            <view class="fz-16 fw-7" :class="{ _skeleton: _loading }">
              <text>相册</text>
            </view>
            <view
              class="fz-14 moreBox"
              :class="{ _skeleton: _loading }"
              @click="navigateTo({ name: 'photoAlbumManage' })"
            >
              <view>更多</view>
              <text class="ali-icon fz-24">&#xe6c7;</text>
            </view>
          </view>
          <PhotoAlbum :list="photoAlbumInfo" :loading="_loading" />
        </view>

        <view class="borderTop pl-15 pr-15">
          <NewsTab @get-title="getNewsTitle" />
        </view>

        <TuiTabbar />
      </view>
      <canvas canvas-id="measureText" type="2d" style="position: fixed; left: -2000rpx"></canvas>
    </view>

    <UniPopup ref="advertisingPopup">
      <view class="advertising-popup" @click="toWelfareCenter()">
        <TImage :src="advertisingImg" width="622rpx" mode="widthFix" border-radius="32rpx" />
        <view @click.stop="closePopup('advertisingPopup')" class="close-btn ali-icon">
          &#xe724;
        </view>
      </view>
    </UniPopup>
    <view v-if="globalConfig?.isEnableAi" class="ai-popup" @click="toAiAssistant">
      <TImage
        src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/aiAssistantSass.png"
        width="160rpx"
        height="168rpx"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  Home  首页 */
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import {
    computed,
    type CSSProperties,
    provide,
    ref,
    unref,
    getCurrentInstance,
    watch,
  } from 'vue';
  import Header from '@/components/Header/index.vue';
  import TabList from './components/tab-list.vue';
  import ActivityItem from '@/components/ActivityItem/index.vue';
  import type { IActivityListResData } from '@/api/activity/types';
  import NewsTab from './components/news-tab.vue';
  import { isArray } from '@/utils/is';
  import { navigateTo, onLoad } from '@/router';
  import { onPageScroll, onPullDownRefresh, onShareAppMessage } from '@dcloudio/uni-app';
  import TuiTabbar from '@/components/Tui-tabbar/Tui-tabbar.vue';
  import Banner from './components/banner.vue';
  import PhotoAlbum from './components/photoAlbum.vue';
  import Special from './components/special.vue';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { ShareTypeEnum } from '@/enums/shareEnum';
  import { TabbarPageEnum } from '@/enums/pageEnum';
  import type { BannerResult, HomeTabResult } from '@/api/dynamicAllocation/types';
  import type { PhotoAlbumListResult } from '@/api/photoAlbum/types';
  import { getHomeData } from '@/api/home';
  import WelfareModule from './components/WelfareModule.vue';
  import type { HomeDataResult } from '@/api/home/types';
  import { queryShopMemberPop } from '@/api/mall';
  import TImage from '@/components/TImage/index.vue';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import { storeToRefs } from 'pinia';
  import { toAIminiProgram } from '@/utils/dynamicConfig';

  const useApp = useAppStoreWithOut();
  const { globalConfig } = storeToRefs(useApp);
  const { setWxSharePath } = useAppShare();

  // https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/level/level_weal.png
  const advertisingImg = ref();
  const toAiAssistant = () => {
    toAIminiProgram('aiChatPage');
  };

  watch(
    globalConfig,
    (val) => {
      if (val) {
        uni.setNavigationBarTitle({
          title: val.name,
        });
        // #ifdef MP
        uni.setBackgroundColor({
          backgroundColorTop: val.themeColor,
          backgroundColor: val?.themeColor,
        });
        // #endif
      }
    },
    { deep: true },
  );

  onLoad(() => {
    getData();
    useApp.getPrivacySetting();
    queryShopMemberPop().then((res) => {
      if (res) {
        advertisingImg.value = res.imgUrl;
        openPopup('advertisingPopup');
      }
    });
  });

  function toWelfareCenter() {
    navigateTo({
      name: 'memberWelfareCenter',
    });
    closePopup('advertisingPopup');
  }

  const _this = getCurrentInstance();
  const openPopup = (ref: string, direction?: string) => {
    (_this?.refs[ref] as any).open(direction);
  };

  const closePopup = (ref: string, direction?: string) => {
    (_this?.refs[ref] as any).close(direction);
  };

  const getBackground = computed(
    () => `linear-gradient(180deg, ${globalConfig.value?.themeColor} 0%, #FFFFFF 100%)`,
  );

  const getHomeHeaderStyles = computed((): CSSProperties => {
    const pageName = globalConfig.value?.name || '';
    const ctx = uni.createCanvasContext('measureText');
    ctx.setFontSize(18);
    const { width: textWidth } = ctx.measureText(pageName);
    const { left } = wx.getMenuButtonBoundingClientRect();
    const padingRight = 10;
    const padingLeft = 0;
    const width = left - padingRight * 2 - padingLeft;
    const textOverflow: CSSProperties = {
      textOverflow: 'ellipsis',
      overflow: 'hidden',
    };
    if (pageName.length <= 10) {
      return { margin: '0 auto' };
    } else {
      const styles: CSSProperties = {
        textAlign: 'right',
        width: width + 'px',
        marginLeft: '10px',
      };
      return Object.assign(styles, textWidth >= width / 2 ? textOverflow : {});
    }
  });

  // 获取首页数据总和
  const _loading = ref(true);
  const bannerInfo = ref<BannerResult[]>([]); // banner
  const diamondRegionInfo = ref<HomeTabResult[]>([]); // 金刚区
  const groupConfigInfo = ref<HomeTabResult[]>([]); // 专题
  const specialLimit = ref(6); // 专题最多展示数量
  const specialTotal = ref(0); // 专题总数
  const activityInfo = ref<IActivityListResData>(); // 活动
  const photoAlbumInfo = ref<PhotoAlbumListResult[]>([]); // 相册
  const memberBenefitsInfo = ref<HomeDataResult['memberBenefitsInfo']>([]); // 专享福利

  const getData = () => {
    getHomeData()
      .then((_r) => {
        bannerInfo.value = _r.bannerInfo;
        diamondRegionInfo.value = _r.diamondRegionInfo;
        specialTotal.value = _r.groupConfigInfo.length;
        groupConfigInfo.value = _r.groupConfigInfo.splice(0, unref(specialLimit));
        activityInfo.value =
          _r.activityInfo && isArray(_r.activityInfo) ? _r.activityInfo[0] : undefined;
        photoAlbumInfo.value = _r.photoAlbumInfo;
        memberBenefitsInfo.value = _r.memberBenefitsInfo;
        _loading.value = false;
        uni.stopPullDownRefresh();
      })
      .catch(() => {
        _loading.value = false;
      });
  };

  // watch(
  //   () => useUser.token,
  //   () => getData(),
  //   {
  //     immediate: true,
  //   },
  // );

  onPullDownRefresh(() => getData());

  const newsTabTitle = ref('');
  function getNewsTitle(title: string) {
    newsTabTitle.value = title;
  }

  onPageScroll(() => {});

  onShareAppMessage(() => {
    const homeShare = useApp.hasShareImgConfig(ShareTypeEnum.home);
    return {
      imageUrl: homeShare?.iconUrl,
      path: setWxSharePath({ name: TabbarPageEnum.BASE_HOME }),
      title: homeShare?.desc,
    };
  });

  provide('tabTitle', newsTabTitle);
</script>
<style lang="scss" scoped>
  .home-title {
    font-size: 36rpx;
    font-weight: bolder;
    line-height: inherit;
    height: inherit;
    white-space: nowrap;
  }
  .ai-popup {
    position: fixed;
    right: 0;
    bottom: 540rpx;
    z-index: 9999;
  }
  .home-bg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 460rpx;
  }
  .container {
    position: relative;
    z-index: 2;
    min-height: 100vh;
    padding-bottom: 50rpx;
  }

  .borderTop {
    padding-top: 40rpx;
    position: relative;
    // border-top: 30rpx solid #f5f5f5;

    .box-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
    }
  }

  .moreBox {
    color: #aaabab;
    display: flex;
    align-items: center;
  }

  .flexCenter {
    justify-content: center;
  }

  .advertising-popup {
    min-height: 800rpx;
    position: relative;
    .close-btn {
      position: absolute;
      right: 0;
      top: 0;
      text-align: center;
      color: rgba($color: #fff, $alpha: 0.4);
      width: 64rpx;
      height: 64rpx;
      font-size: 48rpx;
      line-height: 64rpx;
    }
  }
</style>
